package com.revzone.demo001.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.revzone.demo001.Enum.EnumOperationLog;
import com.revzone.demo001.Enum.EnumTypeValue;
import com.revzone.demo001.config.OperationLog;
import com.revzone.demo001.entity.*;
import com.revzone.demo001.mapper.RolePermissionMapper;
import com.revzone.demo001.mapper.UserRoleMapper;
import com.revzone.demo001.service.RoleService_old;
import com.revzone.demo001.mapper.RoleMapper_old;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
* @author Admin
* @description 针对表【role】的数据库操作Service实现
* @createDate 2025-06-25 10:44:38
*/
@Service
public class RoleServiceImpl_old extends ServiceImpl<RoleMapper_old, Role>
    implements RoleService_old {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    RoleMapper_old roleMapper;
    @Autowired
    UserRoleMapper userAndRoleMapper;
    @Autowired
    RolePermissionMapper rolepermissionMapper;

//    @Override
//    @OperationLog(value = EnumTypeValue.USER_PERMISSIONS, description = EnumOperationLog.ROLE_QUERY)
//    public Result getRoleList(Role role) {
//
//        HashMap<String, Object> map = new HashMap<>();
//        QueryWrapper<Role> wrapper = new QueryWrapper(role);
//        if (role.getStatus() != null) wrapper.eq("status", role.getStatus());
//        List<Role> reFindBy = roleMapper.selectList(wrapper);
//        map.put("data", reFindBy);
//        return Result.success(map);
//    }
    // 公共转换方法
    private Role convertToRole(RoleDTO roleDTO) {
        Role role = new Role();

        role.setRole_name(roleDTO.getRole_name());
        role.setNick_name(roleDTO.getNick_name());
        role.setStatus(roleDTO.getStatus());
        role.setRemarks(roleDTO.getRemarks());
        role.setUpdate_date(LocalDateTime.now());  // 更新修改时间
        return role;
    }

    @Transactional
    @OperationLog(value = EnumTypeValue.USER_PERMISSIONS, description = EnumOperationLog.ROLE_ADDITION)
    public Result setUserList(RoleDTO roleDTO) {

        int insert;
        Integer newRoleId;
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.eq("role_name", roleDTO.getRole_name());
        Role old_role = roleMapper.selectOne(wrapper);

        if (old_role != null) {
            return Result.error("重复角色名！");
        }
        try {
            Role role = convertToRole(roleDTO);
            role.setCreate_date(LocalDateTime.now());
            insert = roleMapper.insert(role);
            if (insert == 0) {
                throw new RuntimeException("角色不存在: " + roleDTO.getRole_name());
            }
            else{
                newRoleId = role.getId();
            }

            // 删除该角色现有的所有权限关联
            // 这一步确保是制空的权限
            rolepermissionMapper.deleteByRoleId(roleDTO.getId());

            List<Integer> foundId= roleMapper.findIdsByPermissionCodes(roleDTO.getPermissions());
            for (Integer permissionId : foundId) {
                if (permissionId == null) {
                    // 如果前端传递了不存在的权限码，这里可以抛异常或跳过
                    // 抛异常可以强制前端传递有效权限码
                    throw new RuntimeException("权限码不存在，请检查。");
                }
                rolepermissionMapper.insert(newRoleId, permissionId); // 插入新的关联
            }

            return Result.success("success");
        } catch (Exception e) {
            return Result.error("新增角色失败！");
        }
    }

    @OperationLog(value = EnumTypeValue.USER_PERMISSIONS, description = EnumOperationLog.ROLE_MODIFICATION)
    public Result updateUserList(RoleDTO roleDTO) {
        int update;
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_name", roleDTO.getRole_name());
        Role old_role = roleMapper.selectById(roleDTO.getId());
        if (!old_role.getRole_name().equals(roleDTO.getRole_name())
                && roleMapper.selectOne(queryWrapper) != null) {
            return Result.error("重复用户名！");
        }

        try {


            Role role = convertToRole(roleDTO);
            role.setId(roleDTO.getId());
            update = roleMapper.updateById(role);
            // 删除该角色现有的所有权限关联
            rolepermissionMapper.deleteByRoleId(roleDTO.getId());
            List<Integer> foundId= roleMapper.findIdsByPermissionCodes(roleDTO.getPermissions());

            for (Integer permissionId : foundId) {
                if (permissionId == null) {
                    // 如果前端传递了不存在的权限码，这里可以抛异常或跳过
                    // 抛异常可以强制前端传递有效权限码
                    throw new RuntimeException("权限码不存在，请检查。");
                }
                rolepermissionMapper.insert(roleDTO.getId(), permissionId); // 插入新的关联
            }
            return Result.success("success");
        } catch (Exception e) {
            return Result.error("编辑角色失败！");
        }
    }
    //级联删除
    @OperationLog(value = EnumTypeValue.USER_PERMISSIONS, description = EnumOperationLog.ROLE_DELETION)
    public Result delUserList(Integer id) {
        try {
            if (id != 0 && id != null) {
                //级联删除

                Role role = roleMapper.selectById(id);
                if (role == null) {
                    throw new RuntimeException("角色不存在: " + id);
                }

                // 2. 删除用户角色关系（先删关联）
                rolepermissionMapper.deleteByRoleId(id);

                // 3. 删除用户
                roleMapper.deleteById(id);
                return Result.success("success");
            }

        } catch (Exception e) {
            return Result.error("删除角色失败！");
        }

        return Result.error("参数错误");
    }

}




